// src/utils/http.ts
import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import { getToken } from './token'
import { ElMessage } from 'element-plus';
import { useAuthSotre } from '@/sotre/authStore';
// 定义接口返回的数据结构
interface ResponseData<T = any> {
    code: number;
    msg: string;
    data: T;
}

class Http {
    private instance: AxiosInstance;

    constructor(config: AxiosRequestConfig) {
        this.instance = axios.create(config);

        // 请求拦截器
        this.instance.interceptors.request.use(
            (config) => {

                let { token } = useAuthSotre();

                console.log("token111111", token);
                // 在发送请求之前做些什么，例如添加token
                //    const token = localStorage.getItem('token');
                // const token = getToken('token')
                // const token ="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..PxZUNSOOCvssBIpMEBLVF8BnLxv_vp1JN803Uq394nM";
                if (token) {
                    config.headers['Authorization'] = `${token}`;
                }
                return config;
            },
            (error) => {
                // 对请求错误做些什么
                return Promise.reject(error);
            }
        );

        // 响应拦截器
        this.instance.interceptors.response.use(
            (response: AxiosResponse<ResponseData>) => {
                // 对响应数据做些什么
                if (response.data.code === 10000) {
                    return response.data.data;
                } else {
                    ElMessage.error(response.data.msg ?? '请求失败')
                    return Promise.reject(response.data.msg);
                }
            },
            (error) => {
                // 对响应错误做些什么
                return Promise.reject(error);
            }
        );
    }

    public get<T>(url: string, params?: Object, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.get(url, params ? { ...config, params } : config);
    }

    public post<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.post(url, data, config);
    }

    public put<T>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.put(url, data, config);
    }

    public delete<T>(url: string, config?: AxiosRequestConfig): Promise<T> {
        return this.instance.delete(url, config);
    }
}

// 创建实例并导出
const http = new Http({
    baseURL: import.meta.env.VITE_BASE_URL, // 设置基础URL
    timeout: 5000, // 请求超时时间
});

export default http;